package com.briup.web.controller.part4;

import com.briup.bean.Student;
import com.briup.bean.Teacher;
import com.briup.exception.StudentException;
import com.briup.exception.TeacherException;
import com.briup.service.ITeacherService;
import com.briup.service.TeacherServiceImpl;
import com.briup.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.sql.SQLException;

@Controller
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired// ioc容器中找到接口类型的对象赋值给service
    private ITeacherService service;//=new teacherServiceImpl();
    @RequestMapping("/findTeacherById")
    @ResponseBody
    public Result findTeacherById(Integer id){
        //调用service层方法
        Teacher t = null;
        try {
            t = service.findTeacherById(id);
        }catch (Exception e){
            e.printStackTrace();
            if(e instanceof TeacherException){
                return new Result(10001,e.getMessage());
            }
            if(e instanceof SQLException){
                // 短信通知 警告 逻辑
                return new Result(10001,e.getMessage());
            }
            //查询失败：
            return new Result(10001,"程序内部错误");
        }
        return Result.success(t);
    }
    @RequestMapping("/addTeacher")
    @ResponseBody
    public Result addTeacher(Teacher t) throws Exception{
        System.out.println(t);//?
        if(t.getId() == 0){
            System.out.println(1/0);
        }
        if(t.getId() == 1){
            throw  new SQLException("sql编写错误");
        }
        return Result.success();
    }
    /*
        如何将异常处理逻辑代码能够在一个类中使用‘
        将异常处理的逻辑 全局的异常处理逻辑
     */

    //异常处理代码：
    //当前类发送所有异常时，自动调用该方法处理该异常
    //@ExceptionHandler(Exception.class)
    //@ExceptionHandler(TeacherException.class)
    //@ExceptionHandler(Student.class)
    //@ExceptionHandler(Exception.class)
    public String handleException(Exception e, Model m){
        System.out.println("处理当前异常："+e.getMessage());
        String msg = e.getMessage();// //可见信息
        if(! (e instanceof TeacherException) ){
            msg = "程序内部错误";
        }
        m.addAttribute("msg",msg);
        return "error";//逻辑视图名  error.jsp
    }
   // @ExceptionHandler(IOException.class)
    public String handleIO(){
        return "error_io";
    }
   // @ExceptionHandler(SQLException.class)
    public String handleSQL(){
        return "error_sql";
    }
    // 前后端分离项目 ： 交互数据格式为json格式
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleREST(Exception e){
        return new Result(10001,e.getMessage());
    }
}
